﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using StateGrid.MDBservice;
using System.IO;
using iTextSharp.text.pdf;

namespace StateGrid.JJBK
{
    class JJBK_MDB : MDBservice.MDBservice
    {
        public override String id
        {
            get
            {
                return "jingjibaokan";
            }
        }

        private JJBK_DAO jjbkDAO = new JJBK_DAO();

        public override void clear()
        {
            base.clear();
        }

        public override String getTest()
        {
            IList<JJBK_FL> r = jjbkDAO.GetAllJJBK_FL();
            String ret = String.Empty;
            foreach (JJBK_FL i in r)
            {
                ret += i.ToString();
            }
            return ret;
        }

        public JJBK_MDB()
        {
            pmTableName = "JJBK_WF";
            formatPmTableName = "JJBK";
            title = "经济报刊";
        }

        public override void setColumnList()
        {
            this.ColumnList = new List<Column>();
            if (hasFormatTable)
            {
                this.ColumnList.Add(new Column("分类编码", OleDbType.WChar, 6));
                this.ColumnList.Add(new Column("索引编码", OleDbType.WChar, 20));
                this.ColumnList.Add(new Column("文件名", OleDbType.WChar, 50));
                this.ColumnList.Add(new Column("标题", OleDbType.WChar, 255));
                this.ColumnList.Add(new Column("作者", OleDbType.WChar, 150));
                this.ColumnList.Add(new Column("年份", OleDbType.SmallInt));
                this.ColumnList.Add(new Column("月份", OleDbType.WChar, 2));
                this.ColumnList.Add(new Column("日期", OleDbType.Date));
                this.ColumnList.Add(new Column("版号", OleDbType.WChar, 5));
                this.ColumnList.Add(new Column("栏目", OleDbType.WChar, 50));
                this.ColumnList.Add(new Column("原文件名", OleDbType.WChar, 50));
                this.ColumnList.Add(new Column("全文", OleDbType.WChar, 10));
                this.ColumnList.Add(new Column("更新日期", OleDbType.Date));
            }
            else
            {
                //未支持
            }
        }

        protected override PM getPM(OleDbDataReader reader, out String err)
        {
            err = String.Empty;
            JJBK_PM pm = new JJBK_PM();
            if (hasFormatTable)
            {
                pm.flbm = reader["分类编码"].ToString().Trim();
                pm.sybm = reader["索引编码"].ToString().Trim();
                pm.wjm = reader["文件名"].ToString().Trim();
                pm.bt = reader["标题"].ToString().Trim();
                pm.zz = reader["作者"].ToString().Trim();
                try
                {
                    pm.nf = int.Parse(reader["年份"].ToString().Trim());
                }
                catch (Exception)
                {
                    pm.nf = 0;
                }
                try
                {
                    pm.yf = int.Parse(reader["月份"].ToString().Trim());
                }
                catch (Exception)
                {
                    pm.yf = 1;
                }
                try
                {
                    if (String.Empty.Equals(reader["日期"].ToString().Trim()))
                    {
                        //err += pm.flbm + "-" + pm.nf + ":" + pm.bt + ":日期为空\n";
                        pm.rq = DateTime.Parse(pm.nf.ToString() + "/" + pm.yf.ToString() + "/1");
                    }
                    else
                        pm.rq = DateTime.Parse(reader["日期"].ToString().Trim());
                }
                catch
                {
                    err += pm.flbm + "-" + pm.nf + ":" + pm.bt + ": 日期\"" + reader["日期"] + "\"出错\n";
                }
                pm.bh = reader["版号"].ToString().Trim();
                pm.lm = reader["栏目"].ToString().Trim();
                pm.ywjm = reader["原文件名"].ToString().Trim();
                pm.qw = reader["全文"].ToString().Trim();
            }
            else
            {
                //不支持
            }
            pm.dlr = user.name;
            pm.fillEmptyStringAsNull();
            return pm;
        }

        public override bool checkPMValid(PM pm, out string errMsg)
        {
            errMsg = String.Empty;
            JJBK_PM jjbk = (JJBK_PM)pm;
            this.openOleDbConnection();
            sqlcmd.CommandText = @"select * from " + formatPmTableName + " where 分类编码=@分类编码 and 年份=@年份 and 标题=@标题 and 作者=@作者";
            sqlcmd.Connection = this.ObjConnection;
            sqlcmd.Parameters.Add(new OleDbParameter("分类编码", jjbk.flbm));
            sqlcmd.Parameters.Add(new OleDbParameter("年份", jjbk.nf));
            sqlcmd.Parameters.Add(new OleDbParameter("标题", jjbk.bt));
            sqlcmd.Parameters.Add(new OleDbParameter("作者", jjbk.zz));
            OleDbDataReader reader = sqlcmd.ExecuteReader();

            if (reader.Read())
            {
                reader.Close();
                sqlcmd.Parameters.Clear();
                return true;
            }
            else
            {
                reader.Close();
                sqlcmd.Parameters.Clear();
                return false;
            }
            //            this.closeOleDbConnection();
        }

        public override string formatData(PM pm)
        {
            //反馈信息
            String result = String.Empty;
            String Empty = "NULL";
            JJBK_PM jjbk = (JJBK_PM)pm;

            jjbk.zz = GlobalMethod.Semicolon(jjbk.zz);
            jjbk.zz = jjbk.zz.Replace("本报记者", "");
            jjbk.zz = jjbk.zz.Replace("记者", "");
            jjbk.bh = jjbk.bh.Substring(jjbk.bh.Length - 2);
            jjbk.wjm = "自动生成";
            //jjbk.qw = "-1";
            jjbk.dlr = user.name;
            jjbk.gxrq = DateTime.Now;
            if (jjbkDAO.GetJJBK_FLByFlbm(jjbk.flbm) == null)
            {
                result += "分类编码" + jjbk.flbm + "不存在 ";
            }
            jjbk.sybm = jjbk.flbm + "-" + jjbk.nf.ToString() + "-" + jjbk.yf.ToString();
            if (Empty.Equals(jjbk.ywjm))
            {
                result += "原文件名（PDF全文）为空 ";
            }
            else
            {
                if (!File.Exists(fileFolder + jjbk.ywjm))
                {
                    result += jjbk.ywjm + " PDF文件不存在";
                }
            }
            if (Empty.Equals(jjbk.bt))
            {
                result += "标题为空 ";
            }
            if (jjbk.nf == 0)
            {
                result += "年份为空 ";
            }

            if (!result.Equals(String.Empty))
            {
                result += " : " + jjbk.nf + "年" + jjbk.zz + "《" + jjbk.bt + "》\n";
            }

            return result;
        }

        public override String insertPM(PM pm)
        {
            JJBK_PM jjbk = (JJBK_PM)pm;
            int back;
            String err = String.Empty;
            //打开连接
            this.openOleDbConnection();
            OleDbCommand sqlcmd = new OleDbCommand();
            if (!String.Empty.Equals(validateTableName(formatPmTableName)))
            {
                sqlcmd.CommandText = @"create Table " + formatPmTableName + @"(月份 char(2), 分类编码 char(6), 索引编码 char(20), 文件名 char(50), 标题 char(255), 作者 char(150), 日期 datetime, 版号 char(5), 栏目 char(100), 原文件名 char(50), 年份 smallint, 全文 char(10), 更新日期 datetime)";
                sqlcmd.Connection = this.ObjConnection;
                try
                {
                    back = sqlcmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    err = e.Message + "\n";
                    return err;
                }
            }

            sqlcmd.CommandText = @"insert into " + formatPmTableName + @"(月份,分类编码,索引编码,文件名,标题,作者,日期,版号,栏目,原文件名,年份,全文,更新日期) values(@月份,@分类编码,@索引编码,@文件名,@标题,@作者,@日期,@版号,@栏目,@原文件名,@年份,@全文,@更新日期)";
            sqlcmd.Connection = this.ObjConnection;
            OleDbParameter parameter;
            sqlcmd.Parameters.Add(new OleDbParameter("月份", jjbk.yf));
            sqlcmd.Parameters.Add(new OleDbParameter("分类编码", jjbk.flbm));
            sqlcmd.Parameters.Add(new OleDbParameter("索引编码", jjbk.sybm));
            sqlcmd.Parameters.Add(new OleDbParameter("文件名", jjbk.wjm));
            sqlcmd.Parameters.Add(new OleDbParameter("标题", jjbk.bt));
            sqlcmd.Parameters.Add(new OleDbParameter("作者", jjbk.zz));
            parameter = new OleDbParameter("日期", OleDbType.DBDate);
            parameter.Value = jjbk.rq;
            sqlcmd.Parameters.Add(parameter);
            sqlcmd.Parameters.Add(new OleDbParameter("版号", jjbk.bh));
            sqlcmd.Parameters.Add(new OleDbParameter("栏目", jjbk.lm));
            sqlcmd.Parameters.Add(new OleDbParameter("原文件名", jjbk.ywjm));
            sqlcmd.Parameters.Add(new OleDbParameter("年份", jjbk.nf));
            sqlcmd.Parameters.Add(new OleDbParameter("全文", jjbk.qw));
            parameter = new OleDbParameter("更新日期", OleDbType.DBDate);
            parameter.Value = jjbk.gxrq;
            sqlcmd.Parameters.Add(parameter);
            try
            {
                back = sqlcmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                err = e.Message + "\n";
            }
            sqlcmd.Parameters.Clear();

            this.closeOleDbConnection();
            return err;
        }

        public override int deletePM(PM pm, out String err)
        {
            int back = 0;
            err = String.Empty;
            JJBK_PM jjbk = (JJBK_PM)pm;
            //打开连接
            this.openOleDbConnection();
            OleDbCommand sqlcmd = new OleDbCommand();
            if (!String.Empty.Equals(validateTableName(formatPmTableName)))
            {
                sqlcmd.CommandText = @"create Table " + formatPmTableName + @"(月份 char(2), 分类编码 char(6), 索引编码 char(20), 文件名 char(50), 标题 char(255), 作者 char(150), 日期 datetime, 版号 char(5), 栏目 char(100), 原文件名 char(50), 年份 smallint, 全文 char(10), 更新日期 datetime)";
                sqlcmd.Connection = this.ObjConnection;
                try
                {
                    back = sqlcmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    err = e.Message + "\n";
                    return 0;
                }
            }
            //sql语句
            sqlcmd.CommandText = @"delete from " + formatPmTableName + " where 分类编码=@分类编码 and 年份=@年份 and 标题=@标题 and 作者=@作者";
            sqlcmd.Connection = this.ObjConnection;
            sqlcmd.Parameters.Add(new OleDbParameter("分类编码", jjbk.flbm));
            sqlcmd.Parameters.Add(new OleDbParameter("年份", jjbk.nf));
            sqlcmd.Parameters.Add(new OleDbParameter("标题", jjbk.bt));
            sqlcmd.Parameters.Add(new OleDbParameter("作者", jjbk.zz));

            try
            {
                back = sqlcmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                err = "Exception: " + e.Message + "\n";
            }
            sqlcmd.Parameters.Clear();
            //            this.closeOleDbConnection();
            return back;
        }
        /* 现在的方法先delete再insert，就不用为每文库写update了
        public override bool updatePM(PM pm)
        {
            ZWQK_PM zwqk = (ZWQK_PM)pm;
            //打开连接
            this.openOleDbConnection();

            //sql语句
            OleDbCommand sqlcmd = new OleDbCommand(@"update ZWQK set 作者=@作者,作者单位=@作者单位,中文主题词=@中文主题词,外文主题词=@外文主题词,国图分类=@国图分类 where 中文篇名=@中文篇名 and 文件名=@文件名", this.ObjConnection);

            sqlcmd.Parameters.Add(new OleDbParameter("作者", zwqk.zz));
            sqlcmd.Parameters.Add(new OleDbParameter("作者单位", zwqk.zzdw));
            sqlcmd.Parameters.Add(new OleDbParameter("中文主题词", zwqk.zwztc));
            sqlcmd.Parameters.Add(new OleDbParameter("外文主题词", zwqk.wwztc));
            sqlcmd.Parameters.Add(new OleDbParameter("国图分类", zwqk.gtfl));
            sqlcmd.Parameters.Add(new OleDbParameter("中文篇名", zwqk.zwpm));
            sqlcmd.Parameters.Add(new OleDbParameter("文件名", zwqk.wjm));
            int back = sqlcmd.ExecuteNonQuery();
            if (back == 0)
            {
                return false;
            }
            //objConnection.Close();
            return true;
        }*/

        public override bool findServerDuplicate(PM pm)
        {
            JJBK_PM jjbk = (JJBK_PM)pm;
            IList<JJBK_PM> result = jjbkDAO.QueryJJBK_PM(jjbk.sybm, jjbk.bt, jjbk.nf.ToString(), jjbk.zz);
            if (result != null && result.Count != 0)
                return true;
            else
                return false;
        }

        public override String insertPMwithUpdateWJM(PM pm)
        {
            String err = String.Empty;
            JJBK_PM jjbk = (JJBK_PM)pm;
            int index;
            index = jjbk.ywjm.LastIndexOf('/');
            int serial;
            if ("ml.".Equals(jjbk.ywjm.Substring(index + 1, 3)))
            {
                serial = 0;
            }
            else
            {

                JJBK_PM maxPm = jjbkDAO.getMaxJJBK_PM(jjbk.flbm, jjbk.nf.ToString(), jjbk.yf.ToString());
                if (maxPm != null)
                {
                    int pos = maxPm.wjm.LastIndexOf('-');
                    int pos2 = maxPm.wjm.LastIndexOf('.');
                    serial = int.Parse(maxPm.wjm.Substring(pos + 1, 4)) + 1;
                }
                else
                {
                    serial = 1;
                }
            }
            index = jjbk.ywjm.LastIndexOf('.');
            String suffixStr;
            if (index >= 0)
                suffixStr = jjbk.ywjm.Substring(index);
            else
                suffixStr = String.Empty;
            String serialStr = "0000" + serial.ToString();
            jjbk.wjm = jjbk.sybm + "-" + serialStr.Substring(serialStr.Length - 4) + suffixStr;
            try
            {
                jjbkDAO.InsertJJBK_PM(jjbk);
            }
            catch (Exception e)
            {
                err += e.Message + "\n";
            }
            return err;
        }

        public override string addOneRecord(PM pm)
        {
            String err = String.Empty;
            JJBK_PM jjbk = (JJBK_PM)pm;
            jjbk.gxrq = DateTime.Now;
            jjbk.eraseNullInEmptyString();
            err += insertPMwithUpdateWJM(pm);
            if (!String.Empty.Equals(err))
                return err;
            String path = "JJBK/";
            path += jjbk.sybm.Substring(0, 2) + "/";
            path += jjbk.sybm.Substring(2, 2) + "/";
            path += jjbk.nf.ToString() + "/";
            path += jjbk.yf.ToString() + "/";

            String srcFile = fileFolder + jjbk.ywjm;
            String destFile = path + jjbk.wjm;
            try
            {
                FTPtransfer.uploadAndCreateDir(destFile, srcFile);
                System.IO.File.Delete(srcFile);
            }
            catch (Exception e)
            {
                err += "Exception: " + e.Message + ",FTP文件传输失败\n";
                jjbkDAO.DeleteJJBK_PM(jjbk.wjm, user.name);
            }
            return err;
        }

    }
}
